/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UINhapLieu.java
 *
 * Created on Jun 14, 2011, 8:59:59 AM
 */
package Implementation.SourceCode.GUI;

import Implementation.SourceCode.DAL.DB_Access;
import Implementation.SourceCode.Utilities.CheckInput_IN;
import Implementation.SourceCode.Utilities.Utilities;
import Implementation.SourceCode.entities.diengiai;
import java.awt.Font;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author mrkingdom75
 */
public class UINhapLieu extends javax.swing.JFrame {

    private static String kieuSo = "1234567890";
    private DefaultTableModel KQmodel;
    private DB_Access db;
    private static String[] colName = {"id","thu_tu","ngay","thang","nam","hoa_don","dien_giai","so_tien"};
    int[] colSize = {30,70,60,60,80,90,620,200};
    private NumberFormat formatter;
    /** Creates new form UINhapLieu */
    public UINhapLieu() {
        initComponents();
        db = new DB_Access();
        formatter = new DecimalFormat("#,###,###");
        setTitle("Báo Cáo Chi - Nhập Liệu - © mrkingdom75@gmail.com");
        setConstraintField();
        setExtendedState(MAXIMIZED_BOTH);
        tblKetQua.setCellSelectionEnabled(false);
        tblKetQua.setColumnSelectionAllowed(false);
        tblKetQua.setRowSelectionAllowed(true);
        loadTableKetQua();
        lblThuTu.setVisible(false);
        txtTenDayDu.setEditable(false);
        dateNgay.setCalendar(Calendar.getInstance());
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.addKeyEventDispatcher(new MyDispatcher());
        txtTongTien.setEditable(false);
        //txtTongTien.setText("5,000,000");
        Calendar cal = Calendar.getInstance();
        loadTongTienTheoNgay(cal);
    }

    private void loadTongTienTheoNgay(Calendar cal){
        try{
            int ngay = cal.get(Calendar.DAY_OF_MONTH);
            int thang = cal.get(Calendar.MONTH)+1;
            int nam = cal.get(Calendar.YEAR);

            Vector<diengiai> sumTien = db.loadTongTienTheoNgay(ngay, thang, nam);
            if(sumTien.size()>0){
                long tongTien = 0;
                for(diengiai dg : sumTien){
                    tongTien += dg.getSotien();
                }
                txtTongTien.setText(formatter.format(tongTien));
            }else{
                txtTongTien.setText("0");
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    private void loadTableKetQua(){
        try{
            Connection conn= db.getConnection(true);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from diengiai order by id desc limit 2000");
            Vector<Vector> vDienGiai = new Vector<Vector>();
            while(rs.next()){
                Vector dg = new Vector();
                dg.add(rs.getString("id"));
                dg.add(rs.getString("thu_tu"));
                dg.add(rs.getString("ngay"));
                dg.add(rs.getString("thang"));
                dg.add(rs.getString("nam"));
                dg.add(rs.getString("hoa_don"));
                dg.add(Utilities.replaceLoadData(rs.getString("dien_giai")));
                dg.add(formatter.format(rs.getLong("so_tien")));
                vDienGiai.add(dg);
            }
            rs.close();
            conn.close();
            Vector<String> columnName = new Vector<String>();
            columnName.add("ID");
            columnName.add("Mã Kho");
            columnName.add("Ngày");
            columnName.add("Tháng");
            columnName.add("Năm");
            columnName.add("Hóa Đơn");
            columnName.add("Diễn Giải");
            columnName.add("Số Tiền");
            KQmodel = new DefaultTableModel(vDienGiai, columnName){
                public boolean isCellEditable(int rowIndex, int mColIndex) {
                    if(mColIndex>0){
                        return true;
                    }return false;
                }
            };

            tblKetQua.setModel(KQmodel);
            
            tblKetQua.getTableHeader().setFont(new Font("Tahoma", 0, 20));
            int rowSize = 50;
            Utilities.setTableProperties(tblKetQua, rowSize, colSize, true);
            tblKetQua.setFont(new Font("Tahoma", 0, 30));            
            
            tblKetQua.getModel().addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent e) {
                    if(tblKetQua.isEditing())        {
                        if(tblKetQua.getSelectedRow()!=-1 && tblKetQua.getSelectedColumn()!=-1){
                            if(!tblKetQua.getModel().getValueAt(tblKetQua.getSelectedRow(), tblKetQua.getSelectedColumn()).toString().isEmpty()){
                                String updateValue = tblKetQua.getModel().getValueAt(tblKetQua.getSelectedRow(), tblKetQua.getSelectedColumn()).toString();
                                String id = tblKetQua.getModel().getValueAt(tblKetQua.getSelectedRow(), 0).toString();
                                if(db.updateTableData("diengiai" ,id, updateValue, colName[tblKetQua.getSelectedColumn()])){
                                    //JOptionPane.showMessageDialog( null , "Cập nhật dữ liệu : " + updateValue + " Thành Công");
                                }
                            }                   
                        }
                    }
                    
                }
            });
        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
        tblKetQua.getColumnModel().getColumn(7).setCellRenderer(rightRenderer);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panHeader = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        panWest = new javax.swing.JPanel();
        panEast = new javax.swing.JPanel();
        panFooter = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        panCenter = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        lblSoTien = new javax.swing.JLabel();
        lblDienGiai = new javax.swing.JLabel();
        txtDienGiai = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtSoTien = new javax.swing.JTextField();
        txtThuTu = new javax.swing.JTextField();
        btnNhap = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblKetQua = new javax.swing.JTable();
        lblBaoLoi = new javax.swing.JLabel();
        dateNgay = new com.toedter.calendar.JDateChooser();
        txtHoaDon = new javax.swing.JTextField();
        lblThuTu = new javax.swing.JLabel();
        txtTenDayDu = new javax.swing.JTextField();
        txtTongTien = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        panHeader.setBackground(new java.awt.Color(0, 102, 0));
        panHeader.setPreferredSize(new java.awt.Dimension(400, 75));
        panHeader.setLayout(new java.awt.BorderLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 48));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Devices-input-tablet-icon.png"))); // NOI18N
        jLabel1.setText("Nhập Liệu");
        panHeader.add(jLabel1, java.awt.BorderLayout.CENTER);

        getContentPane().add(panHeader, java.awt.BorderLayout.NORTH);

        panWest.setBackground(new java.awt.Color(0, 102, 0));
        panWest.setPreferredSize(new java.awt.Dimension(20, 200));

        javax.swing.GroupLayout panWestLayout = new javax.swing.GroupLayout(panWest);
        panWest.setLayout(panWestLayout);
        panWestLayout.setHorizontalGroup(
            panWestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );
        panWestLayout.setVerticalGroup(
            panWestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 374, Short.MAX_VALUE)
        );

        getContentPane().add(panWest, java.awt.BorderLayout.WEST);

        panEast.setBackground(new java.awt.Color(0, 102, 0));
        panEast.setPreferredSize(new java.awt.Dimension(20, 200));

        javax.swing.GroupLayout panEastLayout = new javax.swing.GroupLayout(panEast);
        panEast.setLayout(panEastLayout);
        panEastLayout.setHorizontalGroup(
            panEastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );
        panEastLayout.setVerticalGroup(
            panEastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 374, Short.MAX_VALUE)
        );

        getContentPane().add(panEast, java.awt.BorderLayout.EAST);

        panFooter.setBackground(new java.awt.Color(0, 102, 0));

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 24));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Close_Box_Red.png"))); // NOI18N
        jButton2.setText("Đóng");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panFooterLayout = new javax.swing.GroupLayout(panFooter);
        panFooter.setLayout(panFooterLayout);
        panFooterLayout.setHorizontalGroup(
            panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panFooterLayout.createSequentialGroup()
                .addContainerGap(710, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(18, 18, 18))
        );
        panFooterLayout.setVerticalGroup(
            panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panFooterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(panFooter, java.awt.BorderLayout.SOUTH);

        panCenter.setBackground(new java.awt.Color(255, 255, 255));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel3.setText("Số H.Đơn:");

        lblSoTien.setFont(new java.awt.Font("Tahoma", 0, 24));
        lblSoTien.setText("Số Tiền:");

        lblDienGiai.setFont(new java.awt.Font("Tahoma", 0, 24));
        lblDienGiai.setText("Diễn Giải:");

        txtDienGiai.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        txtDienGiai.setNextFocusableComponent(txtSoTien);
        txtDienGiai.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDienGiaiKeyPressed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel6.setText("Ngày:");

        txtSoTien.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        txtSoTien.setNextFocusableComponent(btnNhap);
        txtSoTien.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtSoTienKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSoTienKeyReleased(evt);
            }
        });

        txtThuTu.setFont(new java.awt.Font("Tahoma", 0, 36));
        txtThuTu.setNextFocusableComponent(txtDienGiai);
        txtThuTu.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtThuTuKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtThuTuKeyReleased(evt);
            }
        });

        btnNhap.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        btnNhap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Process-Accept-icon.png"))); // NOI18N
        btnNhap.setText("Nhập");
        btnNhap.setNextFocusableComponent(txtHoaDon);
        btnNhap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNhapActionPerformed(evt);
            }
        });
        btnNhap.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnNhapKeyPressed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24));
        jLabel4.setText("Mã Kho:");

        tblKetQua.setFont(new java.awt.Font("Tahoma", 0, 14));
        tblKetQua.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblKetQua.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tblKetQuaKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tblKetQua);

        lblBaoLoi.setFont(new java.awt.Font("Tahoma", 0, 24));
        lblBaoLoi.setForeground(new java.awt.Color(204, 0, 0));
        lblBaoLoi.setText("*");

        dateNgay.setDateFormatString("dd-MM-yyyy");
        dateNgay.setFont(new java.awt.Font("Tahoma", 0, 30)); // NOI18N
        dateNgay.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateNgayPropertyChange(evt);
            }
        });

        txtHoaDon.setFont(new java.awt.Font("Tahoma", 0, 36));
        txtHoaDon.setNextFocusableComponent(txtThuTu);
        txtHoaDon.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtHoaDonKeyPressed(evt);
            }
        });

        lblThuTu.setFont(new java.awt.Font("Tahoma", 0, 36));
        lblThuTu.setForeground(new java.awt.Color(0, 153, 0));
        lblThuTu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/button_ok.png"))); // NOI18N
        lblThuTu.setText("V");

        txtTenDayDu.setFont(new java.awt.Font("Tahoma", 0, 36));
        txtTenDayDu.setNextFocusableComponent(txtHoaDon);
        txtTenDayDu.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTenDayDuKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtTenDayDuKeyReleased(evt);
            }
        });

        txtTongTien.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        txtTongTien.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtTongTien.setNextFocusableComponent(btnNhap);
        txtTongTien.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTongTienKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtTongTienKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout panCenterLayout = new javax.swing.GroupLayout(panCenter);
        panCenter.setLayout(panCenterLayout);
        panCenterLayout.setHorizontalGroup(
            panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblSoTien)
                    .addComponent(lblDienGiai))
                .addGap(20, 20, 20)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addComponent(txtSoTien, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addGap(16, 16, 16)
                        .addComponent(dateNgay, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE))
                    .addComponent(txtDienGiai, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtTongTien, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                    .addComponent(btnNhap, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(panCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblBaoLoi)
                .addContainerGap(798, Short.MAX_VALUE))
            .addGroup(panCenterLayout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 762, Short.MAX_VALUE)
                .addGap(36, 36, 36))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(14, 14, 14)
                .addComponent(txtHoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtThuTu, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTenDayDu, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblThuTu, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        panCenterLayout.setVerticalGroup(
            panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panCenterLayout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addComponent(lblBaoLoi)
                .addGap(18, 18, 18)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtThuTu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTenDayDu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblThuTu, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(txtHoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDienGiai, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDienGiai)
                    .addComponent(txtTongTien, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtSoTien, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateNgay, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblSoTien)
                        .addComponent(jLabel6)
                        .addComponent(btnNhap)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(panCenter, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNhapActionPerformed
        try{
        if(txtHoaDon.getText().trim().isEmpty()){
            setBaoLoi("Thông Báo Lỗi : Chưa nhập \"Số Hóa Đơn\" ");
            lblBaoLoi.setVisible(true);
            txtHoaDon.requestFocus();
            return;
        }
        else if(txtThuTu.getText().trim().isEmpty())
            {
            setBaoLoi("Thông Báo Lỗi : Chưa nhập \"Thứ Tự\" ");
            lblBaoLoi.setVisible(true);
            txtThuTu.requestFocus();
            return;
        }
        else if(lblThuTu.getText().equals("no")){
            setBaoLoi("Thông Báo Lỗi : Nhập Sai \"Thứ Tự\" ");
            lblBaoLoi.setVisible(true);
            txtThuTu.requestFocus();
            return;
        }

        else if(txtDienGiai.getText().trim().isEmpty()){
            setBaoLoi("Thông Báo Lỗi : Chưa nhập \"Diễn Giải\" ");
            lblBaoLoi.setVisible(true);
            txtDienGiai.requestFocus();
            return;
        }
        else if(txtSoTien.getText().trim().isEmpty()){
            setBaoLoi("Thông Báo Lỗi : Chưa nhập \"Số Tiền\" ");
            lblBaoLoi.setVisible(true);
            txtSoTien.requestFocus();
            return;
        }else if(dateNgay.getCalendar()==null){
            setBaoLoi("Thông Báo Lỗi : Chưa nhập \"Ngày Tháng\" ");
            lblBaoLoi.setVisible(true);
            dateNgay.requestFocus();
            return;
        }
        // insert to database
        int ngay = dateNgay.getCalendar().get(Calendar.DAY_OF_MONTH);
        int thang = dateNgay.getCalendar().get(Calendar.MONTH)+1;
        int nam = dateNgay.getCalendar().get(Calendar.YEAR);
        String qInsert = "insert into diengiai (id,thu_tu,ngay,thang,nam,hoa_don,dien_giai,so_tien) values (%s,'%s',%s,%s,%s,%s,'%s',%s)";
        Connection conn = db.getConnection(true);
        Statement stmt = conn.createStatement();
        String id = db.lastID("diengiai");
        qInsert = String.format(qInsert, id,  txtThuTu.getText(), ngay+"",""+thang,nam+"", txtHoaDon.getText(), Utilities.replaceInsertData(txtDienGiai.getText()), txtSoTien.getText().replace(",", ""));
        
        int result = stmt.executeUpdate(qInsert) ;
        if(result==1){
            Vector<String> dg = new Vector<String>();
            dg.add(id);
            dg.add(txtThuTu.getText());
            dg.add(ngay+"");
            dg.add(thang+"");
            dg.add(nam+"");
            dg.add(txtHoaDon.getText());
            dg.add(txtDienGiai.getText());
            dg.add(txtSoTien.getText());
            KQmodel.insertRow(0, dg);            
            setBaoLoi("Nhập thành công diễn giải : "+ txtDienGiai.getText());
            resetAll();
            loadTongTienTheoNgay(dateNgay.getCalendar());
            txtHoaDon.requestFocus();
        }else{
            lblBaoLoi.setText("Lỗi kết nối ! Không thể ghi vào cơ sở dữ liệu");
        }
        conn.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }


        
    }//GEN-LAST:event_btnNhapActionPerformed

    private void txtThuTuKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtThuTuKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER || evt.getKeyCode() == KeyEvent.VK_RIGHT){
            txtDienGiai.requestFocus();
        }else if (evt.getKeyCode() == KeyEvent.VK_LEFT){
            //txtThuTu.requestFocus();
        }
    }//GEN-LAST:event_txtThuTuKeyPressed

    private void txtDienGiaiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDienGiaiKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER && txtDienGiai.getText().length()==0){
            txtSoTien.requestFocus();
        }
        else if(evt.getKeyCode() == KeyEvent.VK_SPACE){
            //txtDienGiai.setText(txtDienGiai.getText().substring(0,1).toUpperCase() + txtDienGiai.getText().substring(1, txtDienGiai.getText().length())  );
        }else if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            txtDienGiai.setText(txtDienGiai.getText().substring(0,1).toUpperCase() + txtDienGiai.getText().substring(1)  );
            txtSoTien.requestFocus();
        }else if(evt.getKeyCode() == KeyEvent.VK_LEFT){
//            txtHoaDon.requestFocus();
        }
        
    }//GEN-LAST:event_txtDienGiaiKeyPressed

    private void txtSoTienKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoTienKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            btnNhap.requestFocus();
        }else if(evt.getKeyCode() == KeyEvent.VK_LEFT){
//            txtDienGiai.requestFocus();
        }
    }//GEN-LAST:event_txtSoTienKeyPressed

    private void btnNhapKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnNhapKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            btnNhap.doClick();
        }else if (evt.getKeyCode() == KeyEvent.VK_RIGHT){
//            txtThuTu.requestFocus();
        }else if (evt.getKeyCode() == KeyEvent.VK_LEFT){
//            txtSoTien.requestFocus();
        }
    }//GEN-LAST:event_btnNhapKeyPressed

    private void txtHoaDonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtHoaDonKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            txtThuTu.requestFocus();
        }else if(evt.getKeyCode() == KeyEvent.VK_LEFT){
//            txtThuTu.requestFocus();
        }
    }//GEN-LAST:event_txtHoaDonKeyPressed

    private void txtThuTuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtThuTuKeyReleased
        if(evt.getKeyCode()>0){
            if(!txtThuTu.getText().isEmpty()){
                String thutu = txtThuTu.getText();
                if(thutu.length()>1){
                    if(db.kiemTraThuTu(thutu)){
                        lblThuTu.setText("ok");
                        lblThuTu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/button_ok.png"))); // NOI18N
                        lblThuTu.setVisible(true);
                        txtTenDayDu.setText(db.layTenDayDu(thutu));
                    }else{
                        lblThuTu.setText("no");
                        lblThuTu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/button_cancel.png"))); // NOI18N
                        lblThuTu.setVisible(true);
                        txtTenDayDu.setText("");
                    }
                }else{
                    lblThuTu.setText("no");
                    lblThuTu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/button_cancel.png"))); // NOI18N
                    lblThuTu.setVisible(true);
                    txtTenDayDu.setText("");
                }
            }else{
                lblThuTu.setText("no");
                lblThuTu.setVisible(false);
                txtTenDayDu.setText("");
            }
        }
    }//GEN-LAST:event_txtThuTuKeyReleased

    private void tblKetQuaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblKetQuaKeyReleased
        if(tblKetQua.getSelectedColumn()!=-1 && tblKetQua.getSelectedRow()!=-1){
            if(evt.getKeyCode()==KeyEvent.VK_DELETE){
                if( JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa dòng này không ? ")){
                    int[] selectedRows = tblKetQua.getSelectedRows();
                    for(int row : selectedRows){
                        db.deleteRowById("diengiai",tblKetQua.getModel().getValueAt(row, 0)+"");
                        KQmodel.removeRow(row);
                    }
                }
            }
        }
    }//GEN-LAST:event_tblKetQuaKeyReleased

    private void txtSoTienKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoTienKeyReleased
        if(!txtSoTien.getText().isEmpty()){
            txtSoTien.setText(formatter.format(Long.parseLong(txtSoTien.getText().replace(",", ""))));
        }
    }//GEN-LAST:event_txtSoTienKeyReleased

    private void txtTenDayDuKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTenDayDuKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTenDayDuKeyPressed

    private void txtTenDayDuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTenDayDuKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTenDayDuKeyReleased

    private void txtTongTienKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTongTienKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTongTienKeyPressed

    private void txtTongTienKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTongTienKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTongTienKeyReleased

    private void dateNgayPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateNgayPropertyChange
        if(dateNgay.getCalendar()!=null){
            loadTongTienTheoNgay(dateNgay.getCalendar());
        }
    }//GEN-LAST:event_dateNgayPropertyChange
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UINhapLieu().setVisible(true);
            }
        });
    }
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnNhap;
    private com.toedter.calendar.JDateChooser dateNgay;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblBaoLoi;
    private javax.swing.JLabel lblDienGiai;
    private javax.swing.JLabel lblSoTien;
    private javax.swing.JLabel lblThuTu;
    private javax.swing.JPanel panCenter;
    private javax.swing.JPanel panEast;
    private javax.swing.JPanel panFooter;
    private javax.swing.JPanel panHeader;
    private javax.swing.JPanel panWest;
    private javax.swing.JTable tblKetQua;
    private javax.swing.JTextField txtDienGiai;
    private javax.swing.JTextField txtHoaDon;
    private javax.swing.JTextField txtSoTien;
    private javax.swing.JTextField txtTenDayDu;
    private javax.swing.JTextField txtThuTu;
    private javax.swing.JTextField txtTongTien;
    // End of variables declaration//GEN-END:variables


    private void setConstraintField() {
        txtThuTu.setDocument(new CheckInput_IN(5,"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789"));
        txtHoaDon.setDocument(new CheckInput_IN(5,"0123456789"));
        txtSoTien.setDocument(new CheckInput_IN(30,"0123456789,."));
    }
    
    private void setBaoLoi(String baoloi){
        if(baoloi.length()>100){
            baoloi = baoloi.substring(0,100)+" ...";
            lblBaoLoi.setText(baoloi);
        }else{
            lblBaoLoi.setText(baoloi);
        }
    }

    private void resetAll() {
        txtThuTu.setText("");
        txtHoaDon.setText("");
        txtDienGiai.setText("");
        txtSoTien.setText("");
        txtTenDayDu.setText("");
    }

    private class MyDispatcher implements KeyEventDispatcher {
    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        if (e.getID() == KeyEvent.KEY_RELEASED){
            if (e.getKeyCode() == KeyEvent.VK_F1) {
                Calendar cal=Calendar.getInstance();
                cal.setTime(dateNgay.getDate());
                cal.add(cal.DATE, 1);
                dateNgay.setCalendar(cal);
                loadTongTienTheoNgay(cal);
                return false;
            } else if (e.getKeyCode() == KeyEvent.VK_F2) {
                Calendar cal=Calendar.getInstance();
                cal.setTime(dateNgay.getDate());
                cal.add(cal.DATE, -1);
                dateNgay.setCalendar(cal);
                loadTongTienTheoNgay(cal);
                return false;
            }
        }
        return false;
    }
    }
}
